package com.example.chenchao.douyyin;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.Configurator;
import android.support.test.uiautomator.Direction;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import android.util.Log;
import android.widget.Toast;

import com.example.chenchao.douyyin.utils.MathUtil;
import com.example.chenchao.douyyin.utils.NetWorkUtil;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import okhttp3.Response;

@RunWith(AndroidJUnit4.class)
public class Douyin {
    public Instrumentation mInstrumentation;
    public UiDevice mDevice;
    private String douyinId;
    private String sigNature;
    private String pariseNum;
    private String focusNum;
    private String fansNum;
    private String worksNum;
    private String worksFocusNum;
    private String commentNum;
    private String likeNum;
    private String videoMusicName;
    private String videoTitle;
    private String authorName;
    private String shareNum;
    private String age;
    private static String UNKNOE = "un know";
    private static String BLANK = "blank";
    private String mLastTitle;

    //抖音版本号 :4.2.1
    @Before
    public void setUp(){
        mInstrumentation = InstrumentationRegistry.getInstrumentation();
        mDevice = UiDevice.getInstance(mInstrumentation);
        Context context = InstrumentationRegistry.getContext();
        String pkName= context.getPackageName();
        Configurator configurator = Configurator.getInstance();
        long defalutWaitSelector = configurator.getWaitForSelectorTimeout();
        configurator.setWaitForSelectorTimeout(1000L);
        configurator.setActionAcknowledgmentTimeout(3000L);
        configurator.setScrollAcknowledgmentTimeout(3000L);
        configurator.setKeyInjectionDelay(100L);

    }
    @Test
    public void start(){

        startAPP("com.ss.android.ugc.aweme");
        //跳过广告，如果有
        try{
            UiObject2 object2 = mDevice.wait(Until.findObject(By.text("跳过广告")),2000);
            if(object2!=null){
                object2.click();
            }
        }catch (Exception e){
            Log.e("skip ads",Log.getStackTraceString(e));
        }

        page1();
    }

    private void page1() {

        do{
            Log.e("start","start");
            try{
                UiObject2 object2 = mDevice.wait(Until.findObject(By.textContains("广告")),2000);
                
                if(object2!=null) {//如果是广告视频
                    Context context = InstrumentationRegistry.getContext();
                    //跳过广告
                    Toast.makeText(context,"跳过广告",Toast.LENGTH_SHORT).show();
                    slideToNextVideo();

                    sendParams(true);
                    continue;
                }
                UiObject2 object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/title")),2000);
                if(object==null){
                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/title")),2000);
                }
                authorName = object.getText();
                authorName=authorName.replace("@","");
                authorName=authorName.trim();
                System.out.println(authorName);
                object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/l6")),2000);
                if(object==null){
                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/l6")),2000);
                }
                if(object!=null){
                     videoTitle = object.getText();
                    System.out.println(videoTitle);
                }
                if(videoTitle==null||videoTitle.length()==0){
                    videoTitle = BLANK;
                }
                if(mLastTitle!=null&&videoTitle.contains(mLastTitle)){
                    System.out.println("重复啦");
                    slideToNextVideo();
                    continue;
                }
                //原声名称
//                object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/x8")),2000);
//                if(object==null){
//                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/oh")),2000);
//                }
//                videoMusicName = object.getText();
                if(videoMusicName==null){
                    videoMusicName = UNKNOE;
                }
                System.out.println(videoMusicName);

                object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/c07")),2000);
                if(object==null){
                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/c07")),2000);
                }
                likeNum = object.getText();
                likeNum = MathUtil.converWString(likeNum);
                System.out.println(likeNum);

                object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/bee")),2000);
                if(object==null){
                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/bee")),2000);
                }
                commentNum = object.getText();
                commentNum = MathUtil.converWString(commentNum);
                System.out.println(commentNum);

                object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/b39")),2000);
                if(object==null){
                    object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/b39")),2000);
                }
                if(object!=null) {
                    shareNum = object.getText();
                }
                shareNum = MathUtil.converWString(shareNum);
                System.out.println(shareNum);

                try{
                    int startX = mDevice.getDisplayWidth()*3/4;
                    int endX = mDevice.getDisplayWidth()/8;
                    System.out.println("左滑<<------------------------<<<<");
                    mDevice.swipe(startX,mDevice.getDisplayHeight()/2,endX,mDevice.getDisplayHeight()/2,10);

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                        page2();
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        sendParams(false);


                }catch (Exception e){
                    Log.e("a2",Log.getStackTraceString(e));
                    mDevice.pressBack();

                    sendParams(true);
                }



            }
            catch (Exception e){
                Log.e("a1",Log.getStackTraceString(e));
//                Context context = context = InstrumentationRegistry.getContext();
//                Toast.makeText(context,"跳过广告",Toast.LENGTH_SHORT).show();

                mDevice.pressBack();
            }

        }while (true);


    }

    private void sendParams(boolean isAd) throws Exception {
        Map<String,String> params = new HashMap<>();
        params.put("clientId","A1");


        if(!isAd){
            params.put("handdleWay","SAVETODB");
            params.put("authorId",douyinId);
            params.put("personalSign",sigNature);
            params.put("age",age);
            params.put("fansNum",fansNum);
            params.put("authorLikeNum",pariseNum);
            params.put("focusNum",focusNum);
            params.put("worksNum",worksNum);
            params.put("worksFocusNum",worksFocusNum);

            params.put("videoTitle",videoTitle);
            mLastTitle = videoTitle;

            params.put("authorName",authorName);
            params.put("videoMusicName",videoMusicName);
            params.put("likeNum",likeNum);
            params.put("commentNum",commentNum);
            params.put("shareNum",shareNum);
        }else{
            params.put("likeNum","1");
            params.put("handdleWay","DISCARD");
        }


        NetWorkUtil.send(params, new NetWorkUtil.HttpCallBack() {
            @Override
            public void onFailure() {

            }

            @Override
            public void onResponse(Response response){
                try {
                    if(response.body().string().equals("OK")){
                        slideToNextVideo();

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        });

    }

    private void slideToNextVideo() {
        //滑到下一个视频
        try {
            int t = 1000;
            Thread.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int startY = mDevice.getDisplayHeight()*3/4;
        int endY = mDevice.getDisplayHeight()/4;
        mDevice.swipe(mDevice.getDisplayWidth()/2,startY,mDevice.getDisplayWidth()/2,endY,10);
        try {
            int t = 2000+(int)(Math.random()*5000);
            Thread.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //作者信息页
    public void page2() throws Exception {
        UiObject2 object = mDevice.wait(Until.findObject(By.textStartsWith("抖音号")),2000);
        if(object!=null) {
            douyinId = object.getText();
        }
        if(douyinId!=null) {
            douyinId = douyinId.replace("抖音号: ", "");
        }else{
            douyinId = UNKNOE;
        }

        System.out.println(douyinId);

        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/pz")),2000);
        if(object!=null){
            sigNature = object.getText();
        }else {
            sigNature = UNKNOE;
        }
        System.out.println(sigNature);

        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae5")),2000);
        if(object==null){
            object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae5")),2000);
        }
        if(object!=null){
            pariseNum = object.getText();
        }else {
            pariseNum = UNKNOE;
        }

        pariseNum = MathUtil.converWString(pariseNum);
        System.out.println(pariseNum);

        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae7")),2000);
        if(object==null){
            object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae7")),2000);
        }
        if(object!=null){
            focusNum = object.getText();
        }else{
            focusNum = UNKNOE;
        }

        System.out.println(focusNum);
        focusNum = MathUtil.converWString(focusNum);
        //粉丝数
        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae9")),2000);
        if(object==null){
            object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/ae9")),2000);
        }
        if(object!=null) {
            fansNum = object.getText();
            fansNum = MathUtil.converWString(fansNum);
        }else {
            fansNum = UNKNOE;
        }
        System.out.println(fansNum);
        focusNum = MathUtil.converWString(focusNum);
        object = mDevice.wait(Until.findObject(By.textEndsWith("岁")),2000);

        if(object!=null){
            age = object.getText().replace("岁","");
        }else{
            age = "0";
        }
        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/title").textStartsWith("作品")),2000);
        worksNum = object.getText().replace("作品 ","");
        System.out.println(worksNum);
        worksNum = MathUtil.converWString(worksNum);
        if(worksNum.contains("作品")){
         throw new Exception("worksNum not exist");
        }

        object = mDevice.wait(Until.findObject(By.res("com.ss.android.ugc.aweme:id/title").textStartsWith("喜欢")),2000);
        worksFocusNum = object.getText().replace("喜欢 ","");
        System.out.println(worksFocusNum);
        worksFocusNum = MathUtil.converWString(worksFocusNum);
        mDevice.pressBack();
    }
    @After
    public void tearDown(){

    }
    private void startAPP(String sPackageName){
        Context mContext = InstrumentationRegistry.getContext();

        Intent myIntent = mContext.getPackageManager().getLaunchIntentForPackage(sPackageName);  //通过Intent启动app
        mContext.startActivity(myIntent);
    }

}
